package symbol;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class SymbolTable {
    private final Map<String, Symbol> symbols = new LinkedHashMap<>(); // 符号表
    private final int scopeLevel; // 符号所在层次
    private final int scopeNumber; // 符号所在层次编号

    public SymbolTable(int scopeLevel, int scopeNumber) {
        this.scopeLevel = scopeLevel;
        this.scopeNumber = scopeNumber;
    }

    public boolean addSymbol(Symbol symbol) {
        if (symbols.containsKey(symbol.getName())) {
            System.err.println("符号重复定义: " + symbol.getName());
            return false;
        }
        symbols.put(symbol.getName(), symbol);
        return true;
    }

    // 查找符号（只在当前作用域中查找）
    public Symbol getSymbol(String name) {
        return symbols.get(name);
    }

    // 检查符号是否存在于当前作用域
    public boolean contains(String name) {
        return symbols.containsKey(name);
    }

    public void show() throws IOException {
        for (Symbol symbol : symbols.values()) {
            ScopeStack.symbolWriter.write(scopeNumber + " " + symbol.getName() + " " + symbol.getTypeName() + "\n");
        }

    }

    public int getScopeNumber() {
        return scopeNumber;
    }

    public int getScopeLevel() {
        return scopeLevel;
    }

}
